package com.qingyun.shop.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.entity.SysUser;
import com.qingyun.common.core.domain.model.TiktokProxyVo;
import com.qingyun.common.core.redis.RedisCache;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.security.model.shop.AppLoginUser;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.*;
import com.qingyun.shop.domain.vo.OrderVo;
import com.qingyun.shop.mapper.TiktokUserShopMapper;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Classname PayService
 * @Author dyh
 * @Date 2021/9/18 21:04
 */
@Service
@AllArgsConstructor
public class PayService {


	private ITiktokOrderService orderService;

	private ITiktokOrderItemService orderItemService;

	private ITiktokProxyService proxyService;

	private TiktokUserShopMapper tiktokUserShopMapper;

	private ITiktokOrderSettlementService tiktokOrderSettlementService;

	private ITiktokShopService shopService;

	private ITiktokGoodsService goodsService;

	private final ITiktokProxyBranchConfigService iTiktokProxyBranchConfigService;

	private final ITiktokBranchRecordService branchRecordService;

	private ITiktokProxyBranchConfigService branchConfigService;

	private RedisCache redisCache;

	private RedissonClient redissonClient;



	@Transactional(rollbackFor = Exception.class)
	public OrderVo createOrder(TiktokGoods goods,Long count){
		AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
		SysUser sysUser = appLoginUser.getSysUser();
		TiktokUserShop tiktokUserShop = tiktokUserShopMapper.selectOne(Wrappers.lambdaQuery(TiktokUserShop.class).eq(TiktokUserShop::getUserId, sysUser.getUserId()));
		//创建订单号
		Snowflake snowflake = IdUtil.getSnowflake(1, 1);
		String orderNum = String.valueOf(snowflake.nextId());

		TiktokOrder order = new TiktokOrder();

		//订单详情
		TiktokOrderItem orderItem = new TiktokOrderItem();
		//订单vo
		OrderVo orderVo = new OrderVo();
		//各角色下单金额
		String prodNum = String.valueOf(count);
		BigDecimal proxyPrice = goods.getProxyPrice().multiply(new BigDecimal(prodNum));
		BigDecimal shopPrice = goods.getPrice().multiply(new BigDecimal(prodNum));
		if (SecurityUtils.isProxy()) {
			order.setAmount(proxyPrice);
			orderItem.setAmount(proxyPrice);
			orderVo.setAmount(proxyPrice);
		}else{
			order.setAmount(shopPrice);
			orderItem.setAmount(shopPrice);
			orderVo.setAmount(shopPrice);
		}
		order.setGoodsName(goods.getName());
		order.setShopId(tiktokUserShop.getShopId());
		order.setUserId(sysUser.getUserId());
		order.setSource(2);
		order.setStatus(0);
		order.setCount(goods.getVoideCount());
		order.setCreateTime(new Date());
		order.setOrderNum(orderNum);
		order.setCreateBy(sysUser.getUserName());

		orderItem.setGoodsId(goods.getId());
		orderItem.setGoodsName(goods.getName());
		orderItem.setOrderNum(orderNum);
		orderItem.setQuantity(count);
		orderItem.setCreateTime(new Date());
		orderItemService.save(orderItem);
		orderService.save(order);
		orderVo.setOrderNum(orderNum);
		orderVo.setCount(count);
		orderVo.setTiktokGoods(goods);
		orderVo.setTotalVideoCount(goods.getVoideCount()*count);

		return orderVo;
	}

	@Transactional(rollbackFor = Exception.class)
     public void endOrder(String outTradeNo,String transactionId){

		 TiktokOrder order = orderService.getOne(Wrappers.lambdaQuery(TiktokOrder.class).eq(TiktokOrder::getOrderNum, outTradeNo));
		 if (order.getStatus().equals(1)&&order.getPayTime()!=null) {
		 	throw new ServiceException("订单已支付");
		 }
		 order.setPayTime(new Date());
		 order.setStatus(1);
		 order.setCloseTime(new Date());
		 order.setUpdateTime(new Date());
		if (!orderService.updateById(order)) {
			throw new ServiceException("订单更新失败");
		}

		TiktokShop shop = shopService.getById(order.getShopId());
		TiktokOrderItem one = orderItemService.getOne(Wrappers.lambdaQuery(TiktokOrderItem.class).eq(TiktokOrderItem::getOrderNum, outTradeNo));
		Long goodsId = one.getGoodsId();
		TiktokGoods goods = goodsService.getById(goodsId);
		shop.setVideoCount(shop.getVideoCount()+(goods.getVoideCount()*one.getQuantity()));
        shopService.updateById(shop);

       //插入流水
		TiktokOrderSettlement orderSettlement = new TiktokOrderSettlement();
		orderSettlement.setOrderNum(order.getOrderNum());
		orderSettlement.setPayAmount(order.getAmount());
		orderSettlement.setPayStatus(1);
		orderSettlement.setPayNo(transactionId);
		orderSettlement.setPayType(0);
		tiktokOrderSettlementService.save(orderSettlement);

		//todo 进行分账
		this.startRebate(order,shop,goodsId);
	}


	@Transactional(rollbackFor = Exception.class)
	public Boolean startRebate(TiktokOrder order,TiktokShop shop,Long goodsId){
		if (shop.getProxyId().equals(-1L)) {
			return true;
		}
		if (order.getAmount().doubleValue()<=1.0d) {
			return true;
		}
		TiktokProxyBranchConfig one = iTiktokProxyBranchConfigService.lambdaQuery().eq(TiktokProxyBranchConfig::getProxyId, shop.getProxyId()).one();
		if (ObjectUtil.isNull(one)) {
			return true;
		}
		TiktokBranchRecord tiktokBranchRecord = new TiktokBranchRecord();
		tiktokBranchRecord.setOrderNum(order.getOrderNum());
		tiktokBranchRecord.setSubRole("11");//商家下单11 代理商下单22
		tiktokBranchRecord.setGoodName(order.getGoodsName());
		tiktokBranchRecord.setGoodId(goodsId);
		tiktokBranchRecord.setTotalAmount(order.getAmount());
		tiktokBranchRecord.setUserId(order.getUserId());
		tiktokBranchRecord.setPublicId(shop.getId());
		tiktokBranchRecord.setPublicName(shop.getName());
		tiktokBranchRecord.setCreateTime(new Date());
		TiktokProxy proxy = proxyService.getById(shop.getProxyId());
			//如果是顶级代理
			if(proxy.getParentId().equals(0L)){ //总代理
				BigDecimal rate = NumberUtil.add(one.getOneProxyRatio(), one.getTowProxyRatio());
				BigDecimal branchRate = NumberUtil.mul(order.getAmount(), rate);
				tiktokBranchRecord.setRebateAmount(branchRate);
				tiktokBranchRecord.setProxyId(proxy.getId());
				tiktokBranchRecord.setProxyName(proxy.getName());
				branchRecordService.save(tiktokBranchRecord);
				settingAmount(proxy,branchRate,null);
			}else{

				//二级代理得到的金额
				BigDecimal towRate = NumberUtil.mul(order.getAmount(), one.getTowProxyRatio());
				//针对商家二级代理商
				tiktokBranchRecord.setProxyId(proxy.getId());
				tiktokBranchRecord.setProxyName(proxy.getName());
				tiktokBranchRecord.setRebateAmount(towRate);
				branchRecordService.save(tiktokBranchRecord);
				settingAmount(proxy,towRate,null);

				TiktokProxy parentProxy = proxyService.getById(proxy.getParentId());
				//一级代理得到的金额
				BigDecimal oneRate = NumberUtil.mul(order.getAmount(), one.getOneProxyRatio());
				//针对商家一级代理商
				tiktokBranchRecord.setId(null);
				tiktokBranchRecord.setProxyId(parentProxy.getId());
				tiktokBranchRecord.setProxyName(parentProxy.getName());
				tiktokBranchRecord.setRebateAmount(oneRate);
				branchRecordService.save(tiktokBranchRecord);
				settingAmount(parentProxy,oneRate,null);
			}

		return true;
	}

	public TiktokOrder pcCreateOrder(Long proxyId,Long videoCount){
		TiktokProxyBranchConfig branchConfig = branchConfigService.lambdaQuery().eq(TiktokProxyBranchConfig::getProxyId,proxyId).one();
		BigDecimal price = NumberUtil.mul(branchConfig.getProxyPrice(), videoCount);
		Snowflake snowflake = IdUtil.getSnowflake(1, 1);
		String orderNum = String.valueOf(snowflake.nextId());
		TiktokOrder order=new TiktokOrder();
		order.setGoodsName("转发次数："+videoCount);
		order.setProxyId(proxyId);
		order.setUserId(SecurityUtils.getUser().getUserId());
		order.setSource(1);
		order.setStatus(0);
		order.setAmount(price);
		order.setCreateTime(new Date());
		order.setOrderNum(orderNum);
		order.setCreateBy(SecurityUtils.getUser().getUserName());
		order.setCount(videoCount);
		orderService.save(order);
		return order;
	}

	/**
	 * pc 完结订单
	 * @param outTradeNo
	 * @param transactionId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean pcEndOrder(String outTradeNo,String transactionId){
		RLock lock = redissonClient.getLock("pcPay");
		 if(lock.tryLock()) {
		 	try {
				TiktokOrder order = orderService.getOne(Wrappers.lambdaQuery(TiktokOrder.class).eq(TiktokOrder::getOrderNum, outTradeNo));
				if (order.getStatus().equals(1) && order.getPayTime() != null) {
					throw new ServiceException("订单已支付");
				}
				order.setPayTime(new Date());
				order.setStatus(1);
				order.setCloseTime(new Date());
				order.setUpdateTime(new Date());
				if (!orderService.updateById(order)) {
					throw new ServiceException("订单更新失败");
				}
				TiktokOrderSettlement orderSettlement = new TiktokOrderSettlement();
				orderSettlement.setOrderNum(outTradeNo);
				orderSettlement.setPayNo(transactionId);
				orderSettlement.setPayType(1);
				orderSettlement.setPayAmount(order.getAmount());
				orderSettlement.setPayStatus(1);
				orderSettlement.setCreateTime(new Date());
				tiktokOrderSettlementService.save(orderSettlement);
				redisCache.setCacheObject("pay_status_" + order.getOrderNum(), "success", 5, TimeUnit.MINUTES);

				//添加次数
				TiktokProxy proxy = proxyService.getById(order.getProxyId());
				proxy.setVideoCount(proxy.getVideoCount() + order.getCount());
				proxyService.updateById(proxy);
//				//小于2块不分账
//				if (order.getAmount().doubleValue()<=1.0d) {
//					return true;
//				}
//				//分账
//				TiktokProxyBranchConfig one = iTiktokProxyBranchConfigService.lambdaQuery()
//					.eq(TiktokProxyBranchConfig::getProxyId, proxy.getId()).one();
//				if (ObjectUtil.isNull(one)) {
//					return true;
//				}
//				TiktokBranchRecord tiktokBranchRecord = new TiktokBranchRecord();
//				tiktokBranchRecord.setOrderNum(order.getOrderNum());
//				tiktokBranchRecord.setSubRole("22");//商家下单11 代理商下单22
//				tiktokBranchRecord.setGoodName(order.getGoodsName());
//				tiktokBranchRecord.setTotalAmount(order.getAmount());
//				tiktokBranchRecord.setUserId(order.getUserId());
//				tiktokBranchRecord.setPublicId(proxy.getId());
//				tiktokBranchRecord.setPublicName(proxy.getName());
//				tiktokBranchRecord.setCreateTime(new Date());
//
//				BigDecimal rate = NumberUtil.add(one.getOneProxyRatio(), one.getTowProxyRatio());
//				BigDecimal branchRate = NumberUtil.mul(order.getAmount(), rate);
//				if (proxy.getParentId().equals(0L)) {
//					return true;
//				} else {
//					TiktokProxy parentProxy = proxyService.getById(proxy.getParentId());
//					TiktokProxy oneParent = proxyService.getById(parentProxy.getParentId());
//					//针对商家一级代理商
//					if (ObjectUtil.isNotNull(oneParent) || parentProxy.getParentId().equals(0L)) {
//						tiktokBranchRecord.setId(null);
//						tiktokBranchRecord.setProxyId(parentProxy.getId());
//						tiktokBranchRecord.setProxyName(parentProxy.getName());
//						tiktokBranchRecord.setRebateAmount(branchRate);
//						branchRecordService.save(tiktokBranchRecord);
//						settingAmount(parentProxy, branchRate, null);
//					} else {
//						//二级代理得到的金额
//						BigDecimal towRate = NumberUtil.mul(order.getAmount(), one.getTowProxyRatio());
//						tiktokBranchRecord.setProxyId(parentProxy.getId());
//						tiktokBranchRecord.setProxyName(parentProxy.getName());
//						tiktokBranchRecord.setRebateAmount(towRate);
//						branchRecordService.save(tiktokBranchRecord);
//						settingAmount(proxy, towRate, null);
//
//						//一级代理得到的金额
//						BigDecimal oneRate = NumberUtil.mul(order.getAmount(), one.getOneProxyRatio());
//						tiktokBranchRecord.setId(null);
//						tiktokBranchRecord.setProxyId(oneParent.getId());
//						tiktokBranchRecord.setProxyName(oneParent.getName());
//						tiktokBranchRecord.setRebateAmount(oneRate);
//						branchRecordService.save(tiktokBranchRecord);
//						settingAmount(parentProxy, oneRate, null);
//					}
//				}
			}finally {
				lock.unlock();
			}

		 }
		return true;
	}

	public Boolean settingAmount(TiktokProxy tiktokProxy, BigDecimal usableBalance, BigDecimal freezeBalance){
        tiktokProxy.setUsableBalance(NumberUtil.add(tiktokProxy.getUsableBalance(),usableBalance));
        tiktokProxy.setFreezeBalance(NumberUtil.add(tiktokProxy.getFreezeBalance(),freezeBalance));
        if(ObjectUtil.isNotNull(usableBalance)){
			tiktokProxy.setTotalBalance(NumberUtil.add(tiktokProxy.getTotalBalance(),usableBalance));
		}
        if(ObjectUtil.isNotNull(freezeBalance)){
			tiktokProxy.setTotalBalance(NumberUtil.add(tiktokProxy.getTotalBalance(),freezeBalance));
		}
		boolean b = proxyService.updateById(tiktokProxy);
		return b;
	}



}
